<?php


class Tag {
	
	private $tag_name;
	private $attr;
	private $prop;
	private $contents;
	
	public function __construct($tag_name) {
		$this->tag_name = $tag_name;
		$this->attr = array();
		$this->prop = array();
		$this->contents = '';
	}
	
	public function set_attr($attr, $value) {
		$this->attr[$attr] = $value;
	}
	
	public function get_attr($attr) {
		return isset($this->attr[$attr]) ? $this->attr[$attr] : '';
	}
	
	public function add_prop($prop) {
		$this->prop[$prop] = $prop;
	}
	
	public function remove_prop($prop) {
		unset($this->prop[$prop]);
	}
	
	// For convenience
	public function add_class($class) {
		$this->set_attr('class', 
			trim($this->get_attr('class') . ' ' . $class)
		);
	}	
	
	public function set_contents($value) {
		$this->contents = $value;
	}
	
	public function get_contents($value) {
		return $this->contents;
	}
	
	public function __toString() {
		
		$parts = array($this->tag_name);
		
		foreach ($this->attr as $field => $value) {
			$parts[] = "$field='$value'";
		}
		foreach ($this->prop as $value) {
			$parts[] = $value;
		}
		
		if ($this->contents === '' and in_array($this->tag_name, array('input', 'br'))) {
			 return '<' . implode(' ', $parts) . ' />';
		}
		else {
			$contents = method_exists($this->contents, '__toString') ? $this->contents->__toString() : $this->contents;
			return '<' . implode(' ', $parts) . '>' . $contents . '</' . $this->tag_name . '>';
		}
	}
	
}